<template>
  <el-dialog :visible="isShow" title="新增权限点" width="40%" @close="onClose">
    <el-form ref="permFormRef" :model="permForm" :rules="permFormRules" label-width="110px">
      <el-form-item label="权限名称：" prop="name">
        <el-input v-model="permForm.name" placeholder="请输入权限名称" />
      </el-form-item>
      <el-form-item label="权限标识：" prop="code">
        <el-input v-model="permForm.code" placeholder="请输入权限标识" />
      </el-form-item>
      <el-form-item label="权限描述：">
        <el-input v-model="permForm.description" placeholder="请输入权限描述" />
      </el-form-item>
      <el-form-item label="是否开启：">
        <!-- 开启时 1  关闭时 0 -->
        <el-switch
          v-model="permForm.enVisible"
          active-value="1"
          inactive-value="0"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-row type="flex" justify="center">
        <el-button type="primary" size="mini" @click="submit">确定</el-button>
        <el-button type="info" size="mini" @click="onClose">取消</el-button>
      </el-row>
    </template>
  </el-dialog>
</template>

<script>
import { addPermission, editPermission, getUserPermission } from '@/api/permisson'
export default {
  name: 'PermDialog',
  props: {
    isShow: Boolean,
    type: {
      type: Number,
      default: 1
    },
    pid: {
      type: Number,
      default: 0
    }

  },
  data() {
    return {
      permForm: {
        name: '',
        code: '',
        description: '',
        enVisible: '',
        type: '', // 页面路由权限点 1  按钮权限点 2
        pid: '' // 页面路由权限点 '0'  按钮权限点 'id'
      },
      permFormRules: {
        name: [
          {
            required: true,
            message: '权限点名称不能为空',
            trigger: 'blur'
          }
        ],
        code: [{
          required: true,
          message: '权限点标识不能为空',
          trigger: 'blur'
        }]
      }
    }
  },
  methods: {
    onClose() {
      this.permForm = {
        name: '',
        code: '',
        description: '',
        enVisible: '',
        type: '', // 页面路由权限点 1  按钮权限点 2
        pid: 0 // 页面路由权限点 '0'  按钮权限点 'id'
      }
      this.$refs.permFormRef.resetFields()
      this.$emit('update:isShow', false)
    },
    async submit() {
      try {
        await this.$refs.permFormRef.validate()

        if (this.permForm.id) {
          await editPermission(this.permForm)
          this.$message.success('编辑权限点成功')
        } else {
          // 需要给 type pid 做赋值才可
          this.permForm.type = this.type
          this.permForm.pid = this.pid
          await addPermission(this.permForm)
          this.$message.success('添加权限点成功')
        }
        this.$emit('update-list')
        this.onClose()
      } catch (error) {
        console.log(error)
      }
    },
    async getUserPer(id) {
      this.permForm = await getUserPermission(id)
    }
  }
}
</script>
